"use client"

import { useState, useEffect, useCallback, useRef } from "react"
import Image from "next/image"
import { Play, Heart, MessageSquare, Share2, MoreHorizontal } from "lucide-react"
import { Button } from "@/components/ui/button"
import { Avatar } from "@/components/ui/avatar"
import { Badge } from "@/components/ui/badge"
import { toast } from "@/components/ui/use-toast"
import { usePlayer } from "@/contexts/player-context"
import { Pagination } from "@/components/ui/pagination"
import { Skeleton } from "@/components/ui/skeleton"
import {fetchPlaylist, fetchPlaylistDetail, toggleFavorite} from "@/lib/api-client"
import type { Song } from "@/types/song"
import type { Playlist } from "@/types/playlist"
import { useParams } from "next/navigation"
import CommentSection from "@/components/comments/shared/comment-section"

export default function PlaylistDetailPage() {
  const [playlist, setPlaylist] = useState<Playlist | null>(null)
  const [isLoading, setIsLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)
  const [isFavorited, setIsFavorited] = useState(false)
  const [currentPage, setCurrentPage] = useState(1)
  const [totalPages, setTotalPages] = useState(1)
  const [songs, setSongs] = useState<Song[]>([])

  const { playSong, playQueue } = usePlayer()
  const commentsRef = useRef<HTMLDivElement>(null)
  const params = useParams()
  const playlistId = params.id as string
  const songsPerPage = 20 // 每页显示的歌曲数量

  // 获取歌单详情
  const fetchPlaylistData = useCallback(async () => {
    setIsLoading(true)
    try {
      const data = await fetchPlaylistDetail(playlistId,localStorage.getItem("userId"))
      if (data) {
        setPlaylist(data)
        setIsFavorited(data.isLiked || false)

        // 计算总页数
        const totalSongs = data.songs?.length || 0
        setTotalPages(Math.ceil(totalSongs / songsPerPage))

        // 设置当前页的歌曲
        updateCurrentPageSongs(data.songs || [], currentPage)
      }
    } catch (err) {
      console.error("获取歌单详情失败:", err)
      setError("获取歌单详情失败，请稍后重试")
    } finally {
      setIsLoading(false)
    }
  }, [playlistId, currentPage, songsPerPage])

  // 更新当前页的歌曲
  const updateCurrentPageSongs = (allSongs: Song[], page: number) => {
    const startIndex = (page - 1) * songsPerPage
    const endIndex = startIndex + songsPerPage
    setSongs(allSongs.slice(startIndex, endIndex))
  }

  // 初始加载
  useEffect(() => {
    fetchPlaylistData()
  }, [fetchPlaylistData])

  // 页码变化处理
  const handlePageChange = (page: number) => {
    setCurrentPage(page)
    if (playlist?.songs) {
      updateCurrentPageSongs(playlist.songs, page)
    }
    // 滚动到歌曲列表顶部
    window.scrollTo({ top: document.querySelector("table")?.offsetTop || 0, behavior: "smooth" })
  }

  const scrollToComments = () => {
    commentsRef.current?.scrollIntoView({ behavior: "smooth" })
  }

  const handlePlayAll = useCallback(() => {
    if (playlist?.songs && playlist.songs.length > 0) {
      playQueue(playlist.songs)
      toast({
        title: "开始播放",
        description: "已添加全部歌曲到播放列表",
      })
    }
  }, [playlist, playQueue])

  const handleToggleFavorite = useCallback(async () => {
    if (!playlist) return

    try {

      const userId = localStorage.getItem("userId")
      if (!userId) {
        toast({
          title: "请先登录",
          description: "收藏功能需要登录后使用"
        })
        return
      }

      // 乐观更新UI
      setIsFavorited(!isFavorited)

      // 调用API
      await toggleFavorite({
        contentType: "playlist",
        contentId: playlist.id,
        userId: Number.parseInt(userId),
        action: !isFavorited,
      })

      toast({
        title: isFavorited ? "取消收藏" : "收藏成功",
        description: isFavorited ? "已从收藏夹中移除" : "已添加到收藏夹",
      })
    } catch (err) {
      // 恢复原状态
      setIsFavorited(isFavorited)
      console.error("收藏操作失败:", err)
      toast({
        title: "操作失败",
        description: "请稍后重试"
      })
    }
  }, [isFavorited, playlist])

  const handleShare = useCallback(() => {
    // 保留分享功能的占位符
    toast({
      title: "分享功能",
      description: "分享功能正在开发中",
    })
  }, [])

  const handleSongClick = useCallback(
      (song: Song) => {
        playSong(song)
        toast({
          title: "已添加到播放列表",
          description: `正在播放：${song.title}`,
        })
      },
      [playSong],
  )

  // 加载状态
  if (isLoading) {
    return (
        <div className="min-h-screen bg-white pb-32">
          <div className="container mx-auto px-4 py-6">
            <div className="flex gap-6">
              <Skeleton className="h-[200px] w-[200px] rounded-lg" />
              <div className="flex-1">
                <Skeleton className="h-8 w-2/3 mb-4" />
                <Skeleton className="h-6 w-1/3 mb-4" />
                <Skeleton className="h-6 w-1/4 mb-4" />
                <Skeleton className="h-10 w-[120px] rounded-md" />
              </div>
            </div>
            <div className="mt-8">
              <Skeleton className="h-10 w-full mb-4" />
              {Array.from({ length: 5 }).map((_, index) => (
                  <Skeleton key={index} className="h-16 w-full mb-2" />
              ))}
            </div>
          </div>
        </div>
    )
  }

  // 错误状态
  if (error || !playlist) {
    return (
        <div className="min-h-screen bg-white flex items-center justify-center">
          <div className="text-center">
            <h2 className="text-2xl font-bold mb-2">出错了</h2>
            <p className="text-gray-500 mb-4">{error || "无法加载歌单信息"}</p>
            <Button onClick={() => window.history.back()}>返回上一页</Button>
          </div>
        </div>
    )
  }

  return (
      <div className="min-h-screen bg-white pb-32">
        {/* Playlist Header */}
        <div className="container mx-auto px-4 py-6">
          <div className="flex flex-col md:flex-row gap-6">
            <Image
                src={playlist.cover || "/placeholder.svg"}
                alt={playlist.title}
                width={200}
                height={200}
                className="rounded-lg object-cover"
            />
            <div className="flex-1">
              <h1 className="text-2xl font-bold mb-4">{playlist.title}</h1>
              <div className="flex items-center gap-2 mb-4">
                <Avatar className="w-6 h-6">
                  <Image src="/placeholder.svg" alt={playlist.creator} width={24} height={24} />
                </Avatar>
                <span className="text-sm text-gray-600">{playlist.creator}</span>
                <span className="text-sm text-gray-400">{playlist.createdAt}</span>
              </div>
              <div className="flex flex-wrap gap-2 mb-4">
                {playlist.tags &&
                    playlist.tags.map((tag) => (
                        <Badge key={tag} variant="secondary" className="bg-gray-100">
                          {tag}
                        </Badge>
                    ))}
              </div>
              <div className="flex flex-wrap items-center gap-4">
                <Button onClick={handlePlayAll} className="bg-[#31c27c] text-white hover:bg-[#31c27c]/90">
                  <Play className="w-4 h-4 mr-2" />
                  播放全部
                </Button>
                <Button variant="outline" onClick={handleToggleFavorite}>
                  <Heart className={`w-4 h-4 mr-2 ${isFavorited ? "fill-red-500 text-red-500" : ""}`} />
                  {isFavorited ? "已收藏" : "收藏"}
                </Button>
                <Button variant="outline" onClick={scrollToComments}>
                  <MessageSquare className="w-4 h-4 mr-2" />
                  评论
                </Button>
                <Button variant="outline" onClick={handleShare}>
                  <Share2 className="w-4 h-4 mr-2" />
                  分享
                </Button>
                <Button variant="ghost" size="icon">
                  <MoreHorizontal className={"w-4"} />
                </Button>
              </div>
              <div className="flex gap-8 mt-4 text-sm text-gray-500">
                <div>歌曲数：{playlist.songCount || playlist.songs?.length || 0}</div>
                <div>收藏数：{playlist.favoriteCount || 0}</div>
              </div>
            </div>
            <div className="w-full md:w-64">
              <h3 className="font-bold mb-2">简介</h3>
              <p className="text-sm text-gray-600">{playlist.description}</p>
            </div>
          </div>

          {/* Song List */}
          <div className="mt-8">
            <table className="w-full">
              <thead>
              <tr className="text-gray-500 border-b">
                <th className="pb-4 font-normal text-left w-16">序号</th>
                <th className="pb-4 font-normal text-left">歌曲</th>
                <th className="pb-4 font-normal text-left">歌手</th>
                <th className="pb-4 font-normal text-left">专辑</th>
                <th className="pb-4 font-normal text-right">时长</th>
              </tr>
              </thead>
              <tbody>
              {songs.map((song, index) => (
                  <tr key={song.id} className="hover:bg-gray-50 cursor-pointer" onClick={() => handleSongClick(song)}>
                    <td className="py-4 text-gray-400">{(currentPage - 1) * songsPerPage + index + 1}</td>
                    <td className="py-4">
                      <div className="flex items-center gap-2">{song.title}</div>
                    </td>
                    <td className="py-4">{song.artists}</td>
                    <td className="py-4">{song.album?.title}</td>
                    <td className="py-4 text-right">{song.duration}</td>
                  </tr>
              ))}
              </tbody>
            </table>

            {/* 分页控件 */}
            {totalPages > 1 && (
                <div className="mt-6 flex justify-center">
                  <Pagination currentPage={currentPage} totalPages={totalPages} onPageChange={handlePageChange} />
                </div>
            )}
          </div>

          {/* Comments Section */}
          <div ref={commentsRef} className="mt-12 border-t pt-8">
            <h2 className="text-xl font-bold mb-6">评论</h2>
            <CommentSection contentId={playlistId} contentType="playlist" />
          </div>
        </div>
      </div>
  )
}

